﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using PlanningGIS.ManageUtility;
using PlanningGIS.ManageUtility.Modules;
using PlanningGIS.Util.IO;
using PlanningGIS.Util.Log;
using PlanningGIS.Util.Security;

namespace PlanningGIS.Framework.Controls
{
    /// <summary>
    /// 登录操作
    /// </summary>
    public class LoginContext
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public LoginContext()
        {
            try
            {
                if (File.Exists(_tempInfo))
                {
                    string s = FileHelper.ReadFile(_tempInfo);
                    UserNames = s.Split(';');
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 历史用户名称
        /// </summary>
        public string[] UserNames { get; protected set; }

        /// <summary>
        /// 是否保存用户名称
        /// </summary>
        public bool IsSave { get; set; }

        /// <summary>
        /// 返回的消息
        /// </summary>
        public string Message { get; protected set; }

        /// <summary>
        /// 本地用户信息
        /// </summary>
        private readonly string _tempInfo = AppConfig.StartupPath + "\\Temp\\UserInfo.txt";

        /// <summary>
        /// 当前的错误次数
        /// </summary>
        private int errTimes = 0;
        
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public bool Login(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                Message = "用户名和密码不能为空，请输入用户名和密码！";
                return false;
            }
            if (ManageHelper.Administrator.Equals(username)) //超级管理员
            {
                if (!Encoding.UTF8.GetString(ManageHelper.AdminPassword).Equals(password))
                {
                    Message = "用户名和密码错误，请重新输入！";
                    return false;
                }
                FrameworkHelper.CurrentUser = new User();
                FrameworkHelper.CurrentUser.Parse(new UserInfo()
                {
                    Login_Name = ManageHelper.Administrator,
                    Name = "超级管理员"
                });
                return true;
            }
            try
            {
                Dictionary<string, dynamic> w = new Dictionary<string, dynamic>();
                w.Add("login_name", username);
                List<UserInfo> us = ManageHelper.DBContext.GetAllEntry<UserInfo>(w);
                if (us == null || us.Count == 0)
                {
                    Message = "当前帐号不存在，请重新输入！";
                    return false;
                }
                UserInfo u = us[0];
                if (!"1".Equals(u.IsActive))
                {
                    Message = "当前帐号不可用，请联系管理员！";
                    return false;
                }
                if ("lock".Equals(u.Status))
                {
                    if (ManageHelper.SecuritySet != null && ManageHelper.SecuritySet.LockTime > 0)
                    {
                        if (u.LockedTime.AddMinutes(ManageHelper.SecuritySet.LockTime) > ManageHelper.DBContext.GetSysDateTime())
                        {
                            FrmTimer frm = new FrmTimer();
                            frm.LockedTime = u.LockedTime;
                            frm.Show();
                            return false;
                        }
                    }
                }
                FrameworkHelper.CurrentUser = new User();
                FrameworkHelper.CurrentUser.Parse(u);
                if (ManageHelper.SecuritySet != null && ManageHelper.SecuritySet.PasswordValid > 0)
                {
                    if (u.EffectiveTime.AddMonths(ManageHelper.SecuritySet.PasswordValid) < ManageHelper.DBContext.GetSysDateTime())
                    {
                        Message = "密码已过期，请先修改密码！";
                        FrmUpdatePSD frm = new FrmUpdatePSD();
                        if (frm.ShowDialog() != DialogResult.OK) return false;
                        return true;
                    }
                }
                if (!FrameworkHelper.CurrentUser.PSD.Equals(SecurityHelper.EnCryptUnidirectional(password, AppConfig.SystemConfig.基本信息.密钥)))
                {
                    errTimes += 1;
                    if (ManageHelper.SecuritySet.ErrorNumber > 0)
                    {
                        int n = ManageHelper.SecuritySet.ErrorNumber - errTimes;
                        if (n <= 0)
                        {
                            u.Status = "lock";
                            u.LockedTime = ManageHelper.DBContext.GetSysDateTime();
                            ManageHelper.DBContext.Update<UserInfo>(u, "id", u.ID);
                            errTimes = 0;
                            FrmTimer frm = new FrmTimer();
                            frm.LockedTime = u.LockedTime;
                            frm.Show();
                        }
                        else Message = string.Format("密码输入错误，您还有{0}次输入密码的机会！", n);
                    }
                    else
                    {
                        Message = "密码错误，请重新输入！";
                    }
                    return false;
                }
                try
                {
                    if (IsSave) FileHelper.WriteFile(_tempInfo, username + ";");
                }
                catch
                {

                }
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorText(ex);
                Message = "登录失败！";
                return false;
            }
        }
    }
}
